import React, {Component} from 'react';
// 引入store用于获取redux中保存的状态
import store from "../../redux/countStore/store";

class Count extends Component {
    constructor(props) {
        super(props)
        this.state = {value: 1}
    }

    /*双向数据绑定*/
    changeHandle = (event) => {
        const {value} = event.target
        this.setState({value: Number(value)})
    }

    //加
    increment = () => {
        const {value} = this.state
        store.dispatch({type: "increment", data: value})

    }
    //减
    decrement = () => {
        const {value} = this.state
        store.dispatch({type: "decrement", data: value})
    }

    // 求和为奇数加
    incrementIfAdd = () => {
        let {value} = this.state
        if (store.getState() % 2 !== 0) {
            store.dispatch({type: "increment", data: value})
        }
    }
    //异步加
    incrementAsync = () => {
        let {value} = this.state
        setTimeout(() => {
            store.dispatch({type: "increment", data: value})
        }, 1000)
    }

    componentDidMount() {
        // 使用store.subscribe(callback)检测redux中状态的变化，只要变化了就会调用store.subscribe传入的回调函数
        store.subscribe(() => {
            // 强制更新视图 this.forceUpdate()
            // 调用setState()更新
            this.setState({})
        })
    }

    render() {
        const {value} = this.state
        const {getState} = store
        return (
            <div className="count">
                <h1>当前求和为:{getState()}</h1>
                <select value={value} onChange={this.changeHandle}>
                    <option value="1">1</option>
                    <option value="2">2</option>
                    <option value="3">3</option>
                </select>
                <button onClick={this.increment}>+</button>
                <button onClick={this.decrement}>-</button>
                <button onClick={this.incrementIfAdd}>当前求和为奇数再加</button>
                <button onClick={this.incrementAsync}>异步加</button>
            </div>
        );
    }
}

export default Count;
